package com.dong.service;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

@Component
public class UdpReceiverComponent {
    private DatagramSocket socket;
    private boolean isRunning = false;

    @PostConstruct
    public void startReceiver() {
        isRunning = true;
        new Thread(() -> {
            try {
                socket = new DatagramSocket(9527); // 绑定9999端口
                System.out.println("UDP接收端启动，端口：9999");
                byte[] buffer = new byte[1024];

                while (isRunning) {
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    socket.receive(packet); // 阻塞接收数据

                    //                    // 解析数据
                    //                   int message =
                    //                           Integer.parseInt(packet.getData().toString());
                    // 错误写法：
                    // int message = Integer.parseInt(packet.getData().toString());

                    // 正确写法：
                    // 1. 将字节数组转换为字符串（使用正确的编码，如UTF-8）
                    String dataStr = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
                    // 2. 再解析为整数
                    int message = Integer.parseInt(dataStr);



                    InetAddress senderAddress = packet.getAddress();
                    int senderPort = packet.getPort();
                    System.out.println("收到来自 " + senderAddress + ":" + senderPort + " 的消息：我是udp❤️" + message);
                }
            } catch (Exception e) {
                if (!isRunning) {
                    System.out.println("UDP接收端已关闭");
                } else {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @PreDestroy
    public void stopReceiver() {
        isRunning = false;
        if (socket != null) {
            socket.close();
        }
    }
}

/**
 * import org.springframework.stereotype.Component;
 * import java.net.DatagramPacket;
 * import java.net.DatagramSocket;
 * import java.net.InetAddress;
 *
 * @Component
 * public class UdpSenderComponent {
 *
 *     // 发送UDP消息
 *     public void sendMessage(String host, int port, String message) {
 *         try (DatagramSocket socket = new DatagramSocket()) {
 *             byte[] data = message.getBytes();
 *             InetAddress address = InetAddress.getByName(host);
 *
 *             // 封装数据报
 *             DatagramPacket packet = new DatagramPacket(
 *                 data, data.length, address, port
 *             );
 *             socket.send(packet); // 发送
 *             System.out.println("UDP消息已发送");
 *         } catch (Exception e) {
 *             e.printStackTrace();
 *         }
 *     }
 * }
 */
